qui(function (require, exports, module) {
    Record.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            operator_plan_list: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='Record.Util.openPlanModifyDlg(" + r.id + ")'>修改</a>");
                if (r.enable == 1) {
                    htmlArr.push("<a class='disabled'>删除</a> ");
                } else {
                    htmlArr.push("<a href='javascript:;' onclick='Record.Util.delPlan(" + r.id + ")'>删除</a>");
                }
                return htmlArr.join("&nbsp;");
            },
            category: function (v, o, r) {
                var resultData = Record.Dao.getDataByName("lego_category");
                var ret = "";
                $.each(resultData.data, function (i, element) {
                    if (element.id == v) {
                        ret = element.name;
                        return false;
                    }
                })
                return ret;
            },
            hasAuth: function (v, o, r) {
                return v == 1 ? "有" : "无";
            },
            enable: function (v, o, r) {
                return v == 1 ? "启用" : "禁用";
            },
            planType: function (v, o, r) {
                var ret = "未设定";
                switch (v) {
                    case 1 :
                        ret = "循环输出";
                        break;
                    case 2:
                        ret = "全时输出";
                        break;
                }
                return ret;
            },
            planRule: function (v, o, r) {
                var retArr = [];
                if (r.planType == 1) {
                    retArr.push("重复周期:" + Record.Util.decodeRepeatCode(r.repeatCode, "ch") + "<br>");
                    retArr.push("收录日期:" + r.startDate + "至" + r.stopDate + "<br>");
                    retArr.push("收录时间:" + r.startDayTime + "至" + r.stopDayTime + "<br>");
                } else if (r.planType == 2) {
                    retArr.push("收录日期:" + r.startDate + "至" + r.stopDate + "<br>");
                    retArr.push("分段时间:" + r.fragmentOutput + "分钟<br>");
                }
                return retArr.join("");
            },
            operator_task_list: function (v, o, r) {
                var htmlArr = [];
                if (r.taskStatus == Record.Config.TASK_STATUS_ENUM_VALUE.WAIT) {
                    htmlArr.push("<a href='javascript:;' onclick='Record.Util.changeTaskStatus(" + r.id + ")'>取消</a>");
                }
                return htmlArr.join();
            },
            taskStatus: function (v, o, r) {
                var ret = Record.Config.TASK_STATUS_TAB["key" + v];
                if (ret == null) {
                    return "";
                }
                return ret;
            },
            elementName: function (v, o, r) {
                return r.colName + "_" + r.taskStartTime.replace(/[-: ]/g, "").substring(0, 12);
            },
            operator_channel_list: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='Record.Util.openChannelModifyDlg(" + r.id + ")'>修改</a>");
                htmlArr.push("<a href='javascript:;' onclick='Record.Util.delChannel(" + r.id + ")'>删除</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/record_channel_signal.html?channel_id=" + r.id + "' target='_blank' onclick=''>信号关联</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/recordcol.html?channel_id=" + r.id + "&channel_name=" + encodeURI(r.channelName) + "' target='_blank'>栏目列表</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/record_plan.html?channel_id=" + r.id + "&channel_name=" + encodeURI(r.channelName) + "' target='_blank'>计划列表</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/record_task.html?channel_id=" + r.id + "&channel_name=" + encodeURI(r.channelName) + "' target='_blank'>任务列表</a>");
                return htmlArr.join("&nbsp;");
            },
            task_range_time: function (v, o, r) {
                return r.taskStartTime + "\n" + r.taskStopTime;
            },
            hasCaption: function (v, r) {
                return Record.Config.CHANNEL_HASCAPTION_ARR[v];
            },
            operator_channelSignalTable_list: function (v, o, r) {
                var htmlArr = [];
                if (r.videoStatus == 100) {
                    htmlArr.push("<a href='' target='_blank'>审核打点</a>");
                }
                return htmlArr.join("&nbsp;");
            },
            videoStatus: function (v, r) {
                var ret = Record.Config.VIDEO_STATUS[v];
                if (ret == null) {
                    return "";
                }
                return ret;
            },
        },
        decodeRepeatCode: function (value, retType) {
            var retArr = [];
            $.each(Record.Config.REPEAT_CODE_ARR, function (i, codeValue) {
                if ((value & codeValue) == codeValue) {
                    retArr.push(i);
                }
            })
            if (retType != null && retType == "ch") {
                $.each(retArr, function (index, val) {
                    retArr[index] = Record.Config.REPEAT_CODE_CH_ARR[val];
                })
            } else {
                $.each(retArr, function (index, val) {
                    retArr[index] = Record.Config.REPEAT_CODE_ARR[val];
                })
            }
            if (retArr.length == 0) {
                retArr.push("未设定");
            }
            return retArr;
        },

        reloadHandler: function (data, tableId) {
            if (data != null) {
                Record.Util.logTips({content: data.msg ? data.msg : "创建成功", theme: data.code == "A00000" ? "success" : "error"});
                if (data.code == "A00000") {
                    if (tableId != null) {
                        $(tableId).trigger("reloadGrid")
                    } else {
                        $("#list").trigger("reloadGrid")
                    }
                }
            } else {
                console.log("callbackHandler no return data");
            }
        },
        checkValidPlanMode: function (entity) {
            if (entity.projectWorkers.length > 2 && entity.notifyType == 0) {
                Record.Util.logTips({ theme: "error", content: "请选择通知方式"});
                return false;
            }
            if (isNaN(entity.channelId)) {
                console.log(entity)
                Record.Util.logTips({ theme: "error", content: "请填写有效频道"});
                return false;
            }
            if (isNaN(entity.colId)) {
                Record.Util.logTips({ theme: "error", content: "请填写有效栏目"});
                return false;
            }
            if (entity.projectWorkers.length > 2 && entity.notifyType == 0) {
                Record.Util.logTips({ theme: "error", content: "请选择通知方式"});
                return false;
            }
            var checkArr = [];
            checkArr.push({value: entity.startDate, error: "开始日期格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                var rule = /^\d{4}-\d{2}-\d{2}$/;
                return rule.test(checkValue);
            }  })
            checkArr.push({value: entity.stopDate, error: "结束日期格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                var rule = /^\d{4}-\d{2}-\d{2}$/;
                return rule.test(checkValue);
            }  })


            if (entity.planType == 1) {
                checkArr.push({value: entity.startDayTime, error: "开始时间格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                    var rule = /^\d{2}:\d{2}:\d{2}$/;
                    return rule.test(checkValue);
                } })
                checkArr.push({value: entity.stopDayTime, error: "结束时间格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                    var rule = /^\d{2}:\d{2}:\d{2}$/;
                    return rule.test(checkValue);
                } })
                checkArr.push({value: entity.repeatCode, error: "重复周期没有选择", type: "gt", other: 0});
            } else if (entity.planType == 2) {
                checkArr.push({value: entity.fragmentOutput, error: "输出时间设置为0", type: "gt", other: 0});
            }

            checkArr.push({value: entity.channelId, error: "输出时间设置为0", type: "gt", other: 0});


            if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                console.log("interrupt checkValidPlanMode")
                return false;
            }
            return true;
        },

        preparePlanMode: function () {
            var sendData = {};
            var parentDom = $("form[role=addForm]");
            var tempId = parseInt(parentDom.find("input[name=edit_plan_id]").val());
            if (tempId > 0) {
                sendData.id = tempId;
            }

            sendData.channelId = parseInt(parentDom.find("input[name=channel_name]").suggest("getValue"));
            sendData.colId = parseInt(parentDom.find("select[name=col_name]").val());
            sendData.enable = parseInt(parentDom.find("select[name=enable]").val());
            sendData.status = 1;
            sendData.planType = parseInt(parentDom.find("input[name=plan_type]:checked").val());
            sendData.startDate = parentDom.find("input[name=start_date]").val();
            sendData.stopDate = parentDom.find("input[name=stop_date]").val();
            if (sendData.planType == 1) {
                sendData.startDayTime = parentDom.find("input[name=start_day_time]").val();
                sendData.stopDayTime = parentDom.find("input[name=stop_day_time]").val();
                sendData.repeatCode = Record.Util.calculateRepeatCodeValue(parentDom.find(".chosen-select").val())
                sendData.fragmentOutput = 0;
            } else if (sendData.planType == 2) {
                sendData.startDayTime = "";
                sendData.stopDayTime = "";
                sendData.repeatCode = 0;
                sendData.fragmentOutput = Record.Util.calculateFragmentOutput(parentDom.find("input[name=fragment_output_hour]").val(), parentDom.find("input[name=fragment_output_minute]").val());
            }
            var notifyType = Record.Util.calculateNotifyType(parentDom.find("input[name=notify_type]:checked"));
            var newDataArr = Record.Util.calculateProjectWorkers(parentDom.find("span.qui-tag"));

            sendData.notifyType = notifyType;
            sendData.projectWorkers = JSON.stringify(newDataArr);
            return sendData;
        },
        calculateNotifyType: function (notifyTypeArr) {
            var notifyType = 0;
            if (notifyTypeArr.length > 0) {
                $.each(notifyTypeArr, function (i, element) {
                    notifyType += parseInt($(element).val());
                })
            }
            return notifyType;
        },
        calculateProjectWorkers: function (workersArr) {
            var newDataArr = []
            if (workersArr.length > 0) {
                $.each(workersArr, function (i, element) {
                    newDataArr.push({ id: $(element).attr("data-tag-id"), label: $(element).attr("data-tag-label") });
                })
            }
            return newDataArr;
        },
        calculateFragmentOutput: function (hourString, minuteString) {
            var baseTime = 0;

            if ($.trim(hourString).length > 0) {
                baseTime = 60 * parseInt(hourString)
            }
            if ($.trim(minuteString).length > 0) {
                baseTime += parseInt(minuteString)
            }

            return baseTime;
        },
        calculateRepeatCodeValue: function (repeatCodeArr) {
            var repeatCodeValue = 0;
            if (repeatCodeArr != null) {
                $.each(repeatCodeArr, function (i, codeValue) {
                    repeatCodeValue = repeatCodeValue | parseInt(codeValue);
                })
            }
            return repeatCodeValue
        },

        sendAddRecordPlan: function () {
            var sendData = Record.Util.preparePlanMode();
            var flag = Record.Util.checkValidPlanMode(sendData);
            if (flag) {
                console.log(JSON.stringify(sendData));
                $("form[role=addForm]").dialog("close");
                Record.Dao.addRecordPlan({data: JSON.stringify(sendData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Record.Util.reloadHandler(data)
                    } else {
                        Record.Util.logTips({theme: "error", content: "创建失败"});
                    }
                })
            }

        },
        sendEditRecordPlan: function () {
            var sendData = Record.Util.preparePlanMode();
            var flag = Record.Util.checkValidPlanMode(sendData);
            if (flag) {
                console.log(JSON.stringify(sendData));
                Record.Dao.editRecordPlan({data: JSON.stringify(sendData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        if (data.data['retValue'] == -1) {
                            Record.Util.logTips({theme: "error", content: "修改失败"});
                        } else if (data.data['retValue'] == -2) {
                            Record.Util.logTips({theme: "error", content: "启用状态不可修改"});
                        } else if (data.data['retValue'] == 1) {
                            Record.Util.logTips({theme: "success", content: "修改成功"});
                            Record.Util.reloadHandler(data)
                            $("form[role=addForm]").dialog("close")
                        }
                    } else {
                        Record.Util.logTips({theme: "error", content: "修改失败"});
                    }
                })
            }

        },
        delPlan: function (entityId) {
            console.log("wait to do");
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Record.Dao.deleteRecordPlan({id: entityId }, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        },
        sendModifyRecordChannel: function () {
            var sendData = Record.Util.prepareChannelMode();
            Record.Util.checkValidChannelMode(sendData, function (flag) {
                if (flag == 5) {
                    $("form[role=modifyForm]").dialog("close");
                    console.log(JSON.stringify(sendData));
                    if (sendData.id) {
                        Record.Dao.editRecordChannel({data: JSON.stringify(sendData)}, function (data) {
                            if (data != null && data.code == "A00000") {
                                Record.Util.reloadHandler(data);
                                Record.Util.logTips({theme: "success", content: "修改成功"});
                            } else {
                                Record.Util.logTips({theme: "error", content: "修改失败"});
                            }
                        })
                    } else {
                        Record.Dao.addRecordChannel({data: JSON.stringify(sendData)}, function (data) {
                            if (data != null && data.code == "A00000") {
                                Record.Util.reloadHandler(data);
                                Record.Util.logTips({theme: "success", content: "添加成功"});
                            } else {
                                Record.Util.logTips({theme: "error", content: "添加失败"});
                            }
                        })
                    }
                }

                if (flag == 1) {
                    Record.Util.logTips({theme: "error", content: "频道名称不能为空"});
                }

                if (flag == 2) {
                    Record.Util.logTips({theme: "error", content: "频道代码不能为空"});
                }

                if (flag == 3) {
                    Record.Util.logTips({theme: "error", content: "频道名称已存在"});
                }
                if (flag == 4) {
                    Record.Util.logTips({theme: "error", content: "频道代码已存在"});
                }
            })

        },
        delChannel: function (entityId) {
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Record.Dao.delRecordChannel({id: entityId }, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        },
        prepareChannelMode: function () {
            var sendData = {};
            var parentDom = $("form[role=modifyForm]");
            var tempId = parseInt(parentDom.find("input[name=id]").val());
            if (tempId > 0) {
                sendData.id = tempId;
            }
            sendData.channelName = parentDom.find("input[name=channelName]").val().trim();
            sendData.channelCode = parentDom.find("input[name=channelCode]").val().trim();
            sendData.hasCaption = parseInt(parentDom.find("input[name=hasCaption]:checked").val());
            sendData.status = 1;
            return sendData;
        },
        checkValidChannelMode: function (entity, callback) {
            var parentDom = $("form[role=modifyForm]");
            var oldName = parentDom.find("input[name=channelName]").attr('oldV');
            var oldCode = parentDom.find("input[name=channelCode]").attr('oldV');

            if (entity.channelName == '') {
                callback.call(this, 1);
                return;
            }
            if (entity.channelCode == '') {
                callback.call(this, 2);
                return;
            }

            if (oldName && oldName == entity.channelName && oldCode && oldCode == entity.channelCode) {
                callback.call(this, 5);
                return;
            } else {
                Record.Dao.getRecordChannelList({ 'paramsObj': JSON.stringify({'EQS_channelName': entity.channelName})}, function (data) {
                    if (oldName != entity.channelName && data != null && data.code == "A00000" && data.data.totalCount > 0) {
                        //频道名称已存在
                        callback.call(this, 3);
                        return;
                    } else {
                        Record.Dao.getRecordChannelList({ 'paramsObj': JSON.stringify({'EQS_channelCode': entity.channelCode})}, function (data1) {
                            if (oldCode != entity.channelCode && data1 != null && data.code == "A00000" && data1.data.totalCount > 0) {
                                //频道代码已存在
                                callback.call(this, 4);
                                return;
                            } else {
                                callback.call(this, 5);
                            }
                        });
                    }
                });
            }

        },
        openChannelModifyDlg: function (entityId) {
            var parentDom = $("form[role=modifyForm]");
            parentDom.dialog("open");
            parentDom.find("input[name=id]").val("");
            parentDom.find("input[name=channelName]").val("").removeAttr('oldV');
            parentDom.find("input[name=channelCode]").val("").removeAttr('oldV');
            parentDom.find("input[name=hasCaption][value=1]").click();

            if (entityId > 0) {
                Record.Dao.getRecordChannelList({paramsObj: JSON.stringify({EQL_id: entityId})}, function (data) {
                    if (data != null && data.code == "A00000") {
                        console.log(JSON.stringify(data));
                        var result = data.data.result[0];
                        parentDom.find("input[name=id]").val(result.id);
                        parentDom.find("input[name=channelName]").val(result.channelName).attr('oldV', result.channelName);
                        parentDom.find("input[name=channelCode]").val(result.channelCode).attr('oldV', result.channelCode);
                        ;
                        parentDom.find("input[name=hasCaption][value=" + result.hasCaption + "]").click();
                    } else {
                        Record.Util.logTips({theme: "error", content: "访问数据失败"});
                    }
                })
                parentDom.dialog("open");
            } else {

                parentDom.dialog("open");
            }
        },
        logTips: function (options) {
            EpgWeb.Plugin.showTips(options);
        },
        openPlanModifyDlg: function (entityId, flag) {
            Record.Util.doAddFormReset();
            var parentDom = $("form[role=addForm]");
            if (flag && flag == 1 && entityId > 0) {
                Record.Dao.getColList({paramsObj: JSON.stringify({ "EQL_channelId": entityId, "EQI_status": "1" }), dataMode: "simple", pageSize: 100}, function (retData) {
                    Record.Util.fillRelationColSelect(retData);
                    parentDom.dialog("option", "title", "新建计划").dialog('open');
                    parentDom.find("input[name=plan_type][value='1']").click();
                    parentDom.find("button[name=edit_plan_btn]").hide();
                    parentDom.find("button[name=add_plan_btn]").show();
                })
            } else if (entityId > 0) {
                Record.Dao.getRecordPlan(entityId, function (data) {
                    if (data != null && data.code == "A00000") {
                        console.log(JSON.stringify(data));
                        Record.Dao.getRecordChannelList({paramsObj: JSON.stringify({EQL_id: data.data.channelId}), dataMode: "simple"}, function (gdata) {
                            if (gdata != null && gdata.code == "A00000") {
                                parentDom.dialog("option", "title", "修改计划").dialog('open');
                                parentDom.dialog("open");
                                parentDom.find("button[name=add_plan_btn]").hide();
                                parentDom.find("button[name=edit_plan_btn]").show();
                                data.data.channelName = gdata.data.result[0].channelName;
                                Record.Util.doAddFormFillData(data.data);
                            }
                        })
                    } else {
                        Record.Util.logTips({theme: "error", content: "访问数据失败"});
                    }
                })
            } else {
                parentDom.dialog("option", "title", "新建计划").dialog('open');
                parentDom.find("input[name=plan_type][value='1']").click();
                parentDom.find("button[name=edit_plan_btn]").hide();
                parentDom.find("button[name=add_plan_btn]").show();
            }
        },
        doAddFormReset: function () {
            var parentDom = $("form[role=addForm]");
            parentDom[0].reset();
            var channelName = Com.url.getParameter("channel_name");
            var channelId = Com.url.getParameter("channel_id");
            parentDom.find("select[name=col_name]").html("");
            parentDom.find("select[name=enable]").removeAttr('status');
            parentDom.find('input[name="start_date"]').datepicker("option", "maxDate", null);
            parentDom.find('input[name="stop_date"]').datepicker("option", "minDate", null);
            parentDom.find(".chosen-select").val(null);
            parentDom.find(".chosen-select").attr('disabled',false).trigger('chosen:updated')
            parentDom.find("a.qui-tag-remove").click();
            //parentDom.find("input[name=plan_type]").attr("disabled",false);
            parentDom.find("select[name=enable]").trigger('change');
            if(channelName && channelId){
                $("input[name=channel_name]").val( decodeURI(channelName)).attr('disabled','disabled');
                parentDom.find("input[name=channel_name]").suggest("setValue", {id: channelId, label: decodeURI(channelName)});
            }
        },
        doAddFormFillData: function (element) {
            var parentDom = $("form[role=addForm]");
            parentDom.find("input[name=edit_plan_id]").val(element.id);
            parentDom.find("input[name=channel_name]").suggest("setValue", {id: element.channelId, label: element.channelName});
            Record.Dao.getColList({paramsObj: JSON.stringify({ "EQL_channelId": element.channelId, "EQI_status": "1" }), dataMode: "simple", pageSize: 100}, function (retData) {
                Record.Util.fillRelationColSelect(retData, element.colId);
            })
            if (element.projectWorkers != null && element.projectWorkers.length > 2) {
                var workerArr = JSON.parse(element.projectWorkers);
                $.each(workerArr, function (i, element) {
                    parentDom.find("input[name=project_workers]").suggest("addValue", element);
                })
            }
            if ((element.notifyType & 1) == 1) {
                parentDom.find("input[name=notify_type][value='1']").prop("checked", true);
            }
            if ((element.notifyType & 2) == 2) {
                parentDom.find("input[name=notify_type][value='2']").prop("checked", true);
            }
            if ((element.notifyType & 4) == 4) {
                parentDom.find("input[name=notify_type][value='4']").prop("checked", true);
            }
            parentDom.find("select[name=enable]").val(element.enable).attr('status',element.enable);
            parentDom.find("input[name=plan_type][value=" + element.planType + "]").click();

            parentDom.find('input[name="start_date"]').datepicker("setDate", element.startDate);
            parentDom.find('input[name="stop_date"]').datepicker("setDate", element.stopDate);
            parentDom.find('input[name="stop_date"]').datepicker("option", "minDate", element.startDate);
            parentDom.find('input[name="start_date"]').datepicker("option", "maxDate", element.stopDate);
            if (element.planType == 1) {
                parentDom.find('input[name="start_day_time"]').timepicker("setTime", element.startDayTime);
                parentDom.find('input[name="stop_day_time"]').timepicker("setTime", element.stopDayTime);
                parentDom.find('input[name="start_day_time"]').timepicker("option", "minTime", element.startDayTime);
                parentDom.find('input[name="stop_day_time"]').timepicker("option", "maxTime", element.stopDayTime);
                parentDom.find('.chosen-select').val(Record.Util.decodeRepeatCode(element.repeatCode));
                parentDom.find('.chosen-select').trigger('chosen:updated');
            } else if (element.planType == 2) {
                parentDom.find("input[name=fragment_output_hour]").val(element.fragmentOutput / 60 >> 0);
                parentDom.find("input[name=fragment_output_minute]").val(element.fragmentOutput % 60);
            }
            parentDom.find("select[name=enable]").trigger('change');
        },
        fillRelationColSelect: function (retData, colId) {
            var parentDom = $("form[role=addForm]");
            var container = parentDom.find("select[name=col_name]");
            container.html("");
            if (retData != null && retData.code == "A00000") {
                $.each(retData.data.result, function (i, element) {
                    $("<option attr-channel-id='" + element.channelId + "' value='" + element.id + "'>" + element.colName + "</option>").appendTo(container);
                })
            }
            if (colId) {
                parentDom.find("select[name=col_name]").val(colId)
            }
            ;
        },
        changeTaskStatus: function (entityId) {
            SystemDialog.queryConfirm("确认取消任务？", function (flag) {
                if (flag === true) {
                    var sendData = {id: entityId, taskStatus: Record.Config.TASK_STATUS_ENUM_VALUE.TASK_CANCEL}
                    Record.Dao.editRecordTask({data: JSON.stringify(sendData)}, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        }
    });
});